import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Form, Row, Col, Select, Space, Button, DatePicker, message, Skeleton, Radio } from 'antd'
import moment from 'moment'
import style from '../Statistic.module.less'
import SecretarySelect from '@components/SecretarySelect'
import ArbitratorSelect from '@components/ArbitratorSelect'
import Tree from '@components/Tree'
import CauseActionTable from './components/CauseActionTable'
import { strToNum } from '@src/assets/js/tool'
const { Item } = Form
const { Option } = Select

class AllCauseActionStatistic extends Component {
  state = {
    loading: false,
    list: [],
    orderField: '',
    order: '',
    spreadActions: [],
    spreadActionKeys: [],
    treeData: [],
    initialValues: this.getInitialValues(),
    expendKey: [],
    width: 0,
    type: '表格',
    totalCaseNum: 0,
    totalDisputeAmount: 0
  }

  containerRef = React.createRef()
  formRef = React.createRef()

  search () {
    this.getData()
  }

  resetHandle () {
    this.formRef.current.resetFields()
    this.getData()
  }

  // 获取传参
  getParams () {
    const { orderField, order } = this.state
    const form = this.formRef.current.getFieldsValue()
    const condition = []
    const params = {
      type: form.type
    }
    if (orderField && order) {
      params.order = order === 'ascend' ? 'asc' : 'desc'
      params.order_field = orderField
    }
    if (form.begintime) {
      params.begintime = Math.floor(moment(`${form.begintime.format('YYYY-MM-DD')} 00:00:00`) / 1000)
    }
    if (form.endtime) {
      params.endtime = Math.floor(moment(`${form.endtime.format('YYYY-MM-DD')} 23:59:59`) / 1000)
    }
    if (form.processerid) {
      condition.push({ k: 'processerid', o: '=', v: form.processerid })
    }
    if (form.arbitratorid) {
      condition.push({ k: 'arbitratorids', o: 'like', v: `%${form.arbitratorid}%` })
    }
    condition.push({ k: 'status', o: 'not in', v: '未提交,待审核,已提交' })
    params.condition = JSON.stringify(condition)
    return params
  }

  // 获取搜索的案由
  getData () {
    this.setState({ loading: true })
    this.getDataRequest()
      .then(() => {
        this.setState({ loading: false }, () => {
          this.formatTreeFromList()
        })
      })
      .catch(() => this.setState({ loading: false }))
  }

  // 获取搜索案由的数据请求
  getDataRequest () {
    const params = this.getParams()
    return this.$get('/api/xapc/casestat/statCauseActionAllDetail', {
      params
    }).then(res => {
      if (res.status !== 1) {
        return message.warning(res.message)
      }
      const list = res.data.list.map((li, i) => ({ ...li, index: i + 1 }))
      list.push({
        index: '总数',
        casenum: res.data.total,
        disputeamount: res.data.sum_dispute_amount
      })
      this.setState({ list, order: params.order })
    })
  }

  // 获取全部案由数据
  getTotalActionData () {
    return this.$get('/api/common/cause_action')
      .then(res => {
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        const actions = this.getSpreadAction(res.data)
        this.setState({
          spreadActions: actions.map(li => {
            li.title = li.name
            return li
          }),
          spreadActionKeys: actions.map(li => li.name)
        })
      })
  }

  // 初始化获取数据
  initData () {
    this.setState({ loading: true })
    Promise.all([this.getTotalActionData(), this.getDataRequest()])
      .then(res => {
        this.setState({ loading: false }, () => {
          this.formatTreeFromList()
        })
      })
      .catch(() => this.setState({ loading: false }))
  }

  // 获取展开的所有案由
  getSpreadAction (data = []) {
    const result = []
    function spread (arr = [], pName = '') {
      arr.forEach(a => {
        result.push({ name: a.value, pName })
        if (a.children && a.children.length > 0) {
          spread(a.children, a.value)
        }
      })
    }
    spread(data)
    return result
  }

  // 中转数字单位
  transformUnit (n) {
    if (n >= 100000000) {
      return Math.round(n / 1000000) / 100 + '亿'
    }
    return Math.round(n / 100) / 100 + '万'
  }

  // 中转数据格式单位
  formatListData (list) {
    return list.map(li => {
      if (typeof li.disputeamount === 'string' && li.disputeamount) {
        li.disputeamount = Number(li.disputeamount.replace(/,/g, ''))
        if (li.disputeamount) {
          li.disputeamountCn = this.transformUnit(li.disputeamount)
        }
      }
      return li
    })
  }

  // 将搜索的案由排列成树
  formatTreeFromList () {
    this.setState({
      treeData: [],
      expendKey: []
    })
    let { list, spreadActions, spreadActionKeys } = this.state
    list = this.formatListData(list)
    const result = []
    const keyResult = []
    list = list.filter(li => li.index !== '总数')
    function getParentBySonName (name) { // 寻找
      let i = spreadActionKeys.indexOf(name)
      if (i === -1) {
        return null
      }
      i = spreadActionKeys.indexOf(spreadActions[i].pName)
      if (i === -1) {
        return null
      }
      return { ...spreadActions[i], children: [] }
    }
    function loopParent (son) {
      let p = getParentBySonName(son.name)
      if (!p) {
        return false
      }
      son.pName = p.name
      const index = keyResult.indexOf(p.name)
      if (index === -1) {
        p = { ...p, title: p.name, key: p.name, children: [], pName: '' }
        keyResult.push(p.name)
        result.push(p)
      } else {
        p = result[index]
      }
      son.parent = p
      const pKids = p.children.map(li => li.name)
      if (pKids.indexOf(son.name) === -1) {
        p.children.push(son)
      }
      loopParent(p)
    }
    list.forEach(li => {
      if (li.name === '') {
        li.name = '无案由'
      }
      const obj = { ...li, children: [], key: li.name, pName: '' }
      result.push(obj)
      keyResult.push(obj.name)
    })
    list = [...result]
    list.forEach(li => {
      loopParent(li)
    })
    const treeData = result.filter(li => li.pName === '')
    const { totalCaseNum, totalDisputeAmount } = this.computeTotalData(treeData)
    this.setState({
      treeData,
      expendKey: keyResult,
      totalCaseNum,
      totalDisputeAmount
    })
  }

  // 计算总数
  computeTotalData (list) {
    let totalCaseNum = 0
    let totalDisputeAmount = 0
    list.forEach(li => {
      const o = this.computeTotalData(li.children)
      li.totalCaseNum = strToNum(li.casenum) + strToNum(o.totalCaseNum)
      li.totalDisputeAmount = strToNum(li.disputeamount) + strToNum(o.totalDisputeAmount)
      li.totalDisputeAmountCn = this.transformUnit(li.totalDisputeAmount)
      totalCaseNum += strToNum(li.totalCaseNum)
      totalDisputeAmount += strToNum(li.totalDisputeAmount)
    })
    return {
      totalCaseNum,
      totalDisputeAmount
    }
  }

  // 获取初始值
  getInitialValues () {
    const year = moment().year()
    const date = moment(`${year}-01-01 00:00:00`)
    const begintime = moment(date)
    const endtime = moment(date)
    endtime.add(1, 'y')
    endtime.subtract(1, 's')
    const data = {
      type: 'accept_datetime',
      order: 'casenum',
      begintime,
      endtime
    }
    return data
  }

  // 前往查看详情
  toDetail (n) {
    const form = this.formRef.current.getFieldsValue()
    const formData = {
      type: form.type,
      cause_action: [n]
    }
    if (form.begintime) {
      formData.beginTime = form.begintime
    }
    if (form.endtime) {
      formData.endTime = form.endtime
    }
    if (form.processerid) {
      formData.processerid = form.processerid
    }
    if (form.arbitratorid) {
      formData.arbitratorid = form.arbitratorid
    }
    this.props.addWindow({ id: 'AllCaseManage', title: '全委案件', componentName: 'AllCaseManage', forceRefresh: true, meta: { formData } })
  }

  // 限制文本长度
  limitLen (s) {
    if (!s) {
      return s
    }
    return s.length > 30 ? s.slice(0, 30) + '...' : s
  }

  initWidth () {
    this.setState({
      width: this.containerRef.current.offsetWidth - 48
    })
  }

  // 获取百分比
  getPercent (total, num) {
    return Math.ceil(num / total * 10000) / 100 + '%'
  }

  componentDidMount () {
    this.initData()
    this.initWidth()
  }

  renderTreeNode (d) {
    return (
      <span>
        <span>{this.limitLen(d.name)}</span><br />
        {this.renderTreeNodeCaseNum(d)}
        {this.renderTreeNodeMount(d)}
      </span>
    )
  }

  // 渲染案由自身占比
  renderTreeNodeCaseNum (d) {
    if (!d.casenum) {
      return null
    }
    const numPercent = this.getPercent(this.state.totalCaseNum, d.casenum)
    const mountPercent = this.getPercent(this.state.totalDisputeAmount, d.disputeamount)
    return (
      <span>
        <span>{d.casenum}件（{numPercent}）</span>
        <span> / </span>
        <span>{d.disputeamountCn}（{mountPercent}）</span>
        <br />
      </span>
    )
  }

  // 渲染案由及子案由汇总占比
  renderTreeNodeMount (d) {
    if (!d.totalCaseNum || d.casenum === d.totalCaseNum) {
      return null
    }
    const numPercent = this.getPercent(this.state.totalCaseNum, d.totalCaseNum)
    const mountPercent = this.getPercent(this.state.totalDisputeAmount, d.totalDisputeAmount)
    return (
      <span style={{ fontWeight: 'bold' }}>
        <span>汇总：</span>
        <span>{d.totalCaseNum}件（{numPercent}）</span>
        <span> / </span>
        <span>{d.totalDisputeAmountCn}（{mountPercent}）</span>
        <br />
      </span>
    )
  }

  renderTree () {
    if (this.state.loading) {
      return <Skeleton active />
    }
    if (!this.state.loading && this.state.treeData.length) {
      return (
        <Tree data={this.state.treeData} clickNode={(key) => this.toDetail(key)} renderNode={d => this.renderTreeNode(d)} />
      )
    }
  }

  // 根据类型渲染内容
  renderCotentByType () {
    if (this.state.type === '表格') {
      return (
        <CauseActionTable data={this.state.list} loading={this.state.loading} toDetail={d => this.toDetail(d)} />
      )
    }
    return this.renderTree()
  }

  render () {
    return (
      <div className={style.container} ref={this.containerRef}>
        <div className={style['search-box']}>
          <Form ref={this.formRef} labelCol={{ flex: '80px' }} initialValues={this.state.initialValues} onFinish={d => this.search(d)}>
            <Row>
              <Col span={8}>
                <Item label='选择方式' name='type'>
                  <Select placeholder='请选择方式'>
                    <Option value='accept_datetime'>收案</Option>
                    <Option value='docket_datetime'>立案</Option>
                    <Option value='closure_datetime'>结案</Option>
                  </Select>
                </Item>
              </Col>
              <Col span={8}>
                <Item label='开始时间' name='begintime'>
                  <DatePicker placeholder='请选择开始时间' className={style.full} />
                </Item>
              </Col>
              <Col span={8}>
                <Item label='结束时间' name='endtime'>
                  <DatePicker placeholder='请选择结束时间' className={style.full} />
                </Item>
              </Col>
            </Row>
            <Row>
              <Col span={8}>
                <Item label='办案秘书' name='processerid'>
                  <SecretarySelect />
                </Item>
              </Col>
              <Col span={8}>
                <Item label='仲裁员' name='arbitratorid'>
                  <ArbitratorSelect />
                </Item>
              </Col>
              <Col span={8} style={{ textAlign: 'right' }}>
                <Space>
                  <Button type='primary' ghost htmlType='submit'>查询</Button>
                  <Button onClick={() => this.resetHandle()}>重置</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
        <div className={style['table-container']} style={{ width: this.state.width + 'px' }}>
          <div className={style['btn-line']}>
            <Radio.Group value={this.state.type} onChange={e => this.setState({ type: e.target.value })}>
              <Radio.Button value='表格'>表格</Radio.Button>
              <Radio.Button value='树'>树</Radio.Button>
            </Radio.Group>
          </div>
          {this.renderCotentByType()}
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {

  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {

  }
})

export default connect(mapState, mapDispatch)(AllCauseActionStatistic)
